package com.example.pest.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.pest.bean.PTResult;
import com.example.pest.bean.TokenBean;
import com.example.pest.pojo.XxUser;
import com.example.pest.service.impl.XxUserServiceImpl;
import com.example.pest.util.JwtUtil;
import com.example.pest.util.RandomValidateCodeUtil;
import com.example.pest.vo.UserInfo;
import com.example.pest.vo.UserLogin;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;

@Slf4j
@RequestMapping
@RestController
@AllArgsConstructor
public class CommonController {

    @Autowired
    XxUserServiceImpl xxUserService;
    /*
     * 登录
     * */
    @PostMapping("/login")
    public PTResult<UserInfo> login(@RequestBody UserLogin userLogin, HttpServletRequest request) {
        if (!RandomValidateCodeUtil.getInstance().validateCode(request,userLogin.getCode())){
            return PTResult.error("验证码不正确！");
        }
        List<XxUser> all_user = xxUserService.lambdaQuery().eq(XxUser::getPhone, userLogin.getPhone()).list();
        if (all_user.isEmpty()){
            return PTResult.error("用户不存在");
        }
        XxUser user = all_user.get(0);
        if (!user.getPassword().equals(userLogin.getPassword())){
            return PTResult.error("用户名或密码不正确！");
        }
        TokenBean tokenBean = new TokenBean();
        tokenBean.setRole(user.getRole());
        tokenBean.setUserId(user.getId());
        String jwt = JwtUtil.createToken(tokenBean);
        UserInfo userInfo = JSONUtil.toBean(JSONUtil.toJsonStr(user), UserInfo.class);
        userInfo.setToken(jwt);
        return PTResult.ok(userInfo);
    }


    @GetMapping("/getUser")
    public PTResult<UserInfo> getUserInfo() {
        Long userId = JwtUtil.getTokenBean().getUserId();
        XxUser user = xxUserService.getById(userId);
        UserInfo userInfo = JSONUtil.toBean(JSONUtil.toJsonStr(user), UserInfo.class);
        return PTResult.ok(userInfo);
    }

    @PostMapping("/register")
    public PTResult register(@RequestBody XxUser userInfo) {
        QueryWrapper<XxUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("phone", userInfo.getPhone());
        if (xxUserService.count(queryWrapper) > 0){
            return PTResult.error("用户已存在!");
        }
        else {
            XxUser user = JSONUtil.toBean( JSONUtil.toJsonStr(userInfo),XxUser.class);
            user.setId(null);
            user.setUsername("U"+user.getPhone().substring(user.getPhone().length() - 4));
            Date date = new Date();
            user.setCreateTime(date);
            return xxUserService.save(user)  ? PTResult.ok() : PTResult.error("注册失败，请稍后重试！");
        }
    }

    @GetMapping("/code")
    public void getCode(HttpServletRequest request, HttpServletResponse response){
        RandomValidateCodeUtil.getInstance().getRandcode(request,response);
    }

    /**
     * 上传文件
     */
    @PostMapping("/upload")
    public PTResult uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return PTResult.error("文件为空，请选择一个文件上传");
        }

        // Define the upload directory relative to the current running directory
        String uploadDirPath = System.getProperty("user.dir") + File.separator + "upload";
        File uploadDir = new File(uploadDirPath);

        // Create the upload directory if it doesn't exist
        if (!uploadDir.exists()) {
            boolean created = uploadDir.mkdirs();
            if (!created) {
                return PTResult.error("无法创建上传目录，请检查权限");
            }
        }
        String originalFilename = file.getOriginalFilename();
        String uniqueFilename = System.currentTimeMillis() + "_" + originalFilename;
        Path path = Paths.get(uploadDirPath +"/" +uniqueFilename);
        try {
            byte[] bytes = file.getBytes();
            Files.write(path,bytes);
        } catch (IOException e) {
            log.error("文件上传失败", e);
        }
        String filePath = "/download/" + uniqueFilename;
        return PTResult.ok(filePath);
    }

    /**
     * 下载文件
     */
    @GetMapping("/download/{filename}")
    public ResponseEntity<?> downloadFile(@PathVariable String filename) {
        // 定义上传目录的路径
        String uploadDirPath = System.getProperty("user.dir") + File.separator + "upload";
        File file = new File(uploadDirPath, filename);

        if (!file.exists()) {
            return ResponseEntity.status(404).body(PTResult.error("文件不存在"));
        }

        try {
            InputStreamResource resource = new InputStreamResource(new FileInputStream(file));

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"");
            headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(file.length()));
            headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(resource);
        } catch (FileNotFoundException e) {
            log.error("文件下载失败: 文件未找到", e);
            return ResponseEntity.status(500).body(PTResult.error("文件下载失败，请稍后重试"));
        }
    }

}
